/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { View, Dimensions, StyleSheet, FlatList, Button } from 'react-native';
import Video from 'react-native-video';
import { useFocusEffect } from '@react-navigation/native';
import { AdaptiveRotation } from '@hadss/react_native_adaptive_video';
import { videoRotationList, VideoItem } from '../../components/videos';

const VideoSwiper = ({ route, navigation }): JSX.Element => {
  const initialIndex = route.params?.id ?? 0;
  const [currentIndex, setCurrentIndex] = useState(initialIndex);
  const [layoutHeight, setLayoutHeight] = useState(Dimensions.get('window').height);
  const flatRef = useRef<FlatList<VideoItem>>(null);
  const currentIndexRef = useRef(currentIndex);
  currentIndexRef.current = currentIndex;

  // 每次页面重新聚焦时检查 index 是否需要同步
  useFocusEffect(
    useCallback((): void => {
      const idx = route.params?.id;
      if (typeof idx === 'number' && idx !== currentIndexRef.current) {
        setCurrentIndex(idx);
        requestAnimationFrame((): void => {
          flatRef.current?.scrollToIndex({ index: idx, animated: false });
        });
      }
    }, [route.params?.id]),
  );

   useEffect((): (() => void) => {
     const sub = Dimensions.addEventListener('change', ({ window }): void => {
       const h = window.height;
       setLayoutHeight(h);
       requestAnimationFrame((): void => {
         flatRef.current?.scrollToIndex({ index: currentIndexRef.current, animated: false });
       });
     });
     return (): void => sub?.remove();
   }, []);


  const onViewableItemsChanged = useRef(({ viewableItems }): void => {
    if (viewableItems && viewableItems.length > 0) {
      const visibleIndex = viewableItems[0].index;
      if (visibleIndex !== currentIndexRef.current) {
        setCurrentIndex(visibleIndex);
        const video: VideoItem = videoRotationList[visibleIndex];
        AdaptiveRotation.getInstance().setOrientationNotFullScreen({
          width: video.width,
          height: video.height,
        });
      }
    }
  }).current;

  return (
    <FlatList
      ref={flatRef}
      data={videoRotationList}
      pagingEnabled
      renderItem={({ item }):JSX.Element => (
        <View style={[styles.slide, { height: layoutHeight }]}>
          <Video source={item.source} style={[styles.video, { height: layoutHeight * 0.9 }]} resizeMode="contain" muted repeat />
          <Button
            title="进入全屏"
            onPress={(): void => {
              navigation.navigate('Details', { id: item.id });
              AdaptiveRotation.getInstance().setOrientationFullScreen({
                width: item.width,
                height: item.height,
              });
            }}
          />
        </View>
      )}
      keyExtractor={(item): string => String(item.id)}
      getItemLayout={(_, index): { length: number; offset: number; index: number } => ({
        length: layoutHeight,
        offset: layoutHeight * index,
        index,
      })}
      onViewableItemsChanged={onViewableItemsChanged}
      viewabilityConfig={{ viewAreaCoveragePercentThreshold: 80 }}
    />
  );
};

const styles = StyleSheet.create({
  slide: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  video: {
    width: '100%',
    height: '90%',
    zIndex: 1,
  },
  button: {
    left: 50,
    top: 20,
    zIndex: 2,
  },
});

export default VideoSwiper;
